import { defineStore } from 'pinia';
import { LocaleSetting, LocaleType } from '/#/config';
import { LOCALE_KEY } from '/@/enums/cacheEnum';
import { localeSetting } from '/@/settings/localSetting';
import { createLocalStorage } from '/@/utils/cache';
import { store } from '/@/store';

interface LocaleState {
  localInfo: LocaleSetting;
}

const ls = createLocalStorage();
const lsLocalSetting = (ls.get(LOCALE_KEY) || localeSetting) as LocaleSetting;

export const useLocaleStore = defineStore({
  id: 'appLocale',

  state: (): LocaleState => ({
    localInfo: lsLocalSetting,
  }),

  getters: {
    getShowPicker(): boolean {
      return !!this.localInfo?.showPicker;
    },

    getLocale(): LocaleType {
      return this.localInfo?.locale ?? 'zh_CN';
    },
  },

  actions: {
    setLocaleInfo(info: Partial<LocaleSetting>) {
      this.localInfo = { ...this.localInfo, ...info };
      ls.set(LOCALE_KEY, this.localInfo);
    },

    initLocale() {
      this.setLocaleInfo({
        ...localeSetting,
        ...this.localInfo,
      });
    },
  },
});

export function useLocaleStoreWithOut() {
  return useLocaleStore(store);
}
